package com.yixun.qfbao.api.service.impl;

import com.beust.jcommander.Strings;
import com.yixun.qfbao.api.service.*;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.dao.AdviserChangeDao;
import com.yixun.qfbao.enums.QfSmsTemplateEnum;
import com.yixun.qfbao.model.Dictionary;
import com.yixun.qfbao.model.EstateAdviser;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.ReportExternal;
import com.yixun.qfbao.model.dto.DictionaryDto;
import com.yixun.qfbao.model.dto.ReportExternalDto;
import com.yixun.qfbao.model.dto.SmsHistoryDto;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.service.*;
import com.yixun.qfbao.util.DateStyle;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.util.FollowUpListConvert;
import com.yixun.qfbao.util.SMSUtil;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.model.CaseMember;
import com.yixun.qfbao.xf.model.CustomerPremises;
import com.yixun.qfbao.xf.model.FollowUpList;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.CaseMemberDto;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesDto;
import com.yixun.qfbao.xf.model.dto.FollowUpListDto;
import com.yixun.qfbao.xf.model.enums.*;
import com.yixun.qfbao.xf.service.CaseMemberService;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import com.yixun.qfbao.xf.service.FollowUpListService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xiaojin.li
 */
@Service
public class CPFollowUPServiceImpl implements CPFollowUPService {

	private static Logger logger = LoggerFactory.getLogger(SyncFollowAndAffixServiceImpl.class);

	@Autowired
	private CustomerPremisesService customerPremisesService;
	@Autowired
	private PremisesService premisesService;
	@Autowired
	private PartnerInfoService partnerInfoService;
	@Autowired
	private FollowUpListService followUpListService;
	@Autowired
	private AffixService affixService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private CaseMemberService caseMemberService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private SmsHistoryService smsHistoryService;
	@Autowired
	private SmsSettingService smsSettingService;
	@Autowired
	private V10BindService v10BindService;
	@Autowired
	ReportExternalService reportExternalService;
	@Autowired
	private SMSUtil smsUtil;
	@Autowired
	private WxTemplateMsgService wxTemplateMsgService;
	@Autowired
	private EstateAdviserService estateAdviserService;
	@Autowired
	private AdviserChangeDao adviserChangeDao;
	@Autowired
	private ReportCommonService reportCommonService;

	@Override
	public GetCPFollowListResDto getCPFollowList(GetCPFollowListReqDto reqDto)
			throws Exception {
		GetCPFollowListResDto res = new GetCPFollowListResDto();
		FollowUpListDto entity = new FollowUpListDto();
		entity.setCustomerPremisesId(reqDto.getCustomerPremisesId());
		// 非渠道或总代公司不能查看内部跟进类型
		if (!reqDto.getLoginType().equals(SystemIdEnum.DEVELOPERS.getCode())
				&& !reqDto.getLoginType().equals(SystemIdEnum.ADMIN.getCode())
				&& !reqDto.getLoginType().equals(SystemIdEnum.ASSISTANT.getCode())
				&& !reqDto.getLoginType().equals(SystemIdEnum.APP_ASSISTANT.getCode())) {
			entity.setFollowTypes("1,2");
		}
		entity.setOrders(" t.create_time desc");
		entity.setSql("t.new_customer_status!=7");
		List<FollowUpList> fulist = followUpListService.selectListByDto(entity);
		List<FollowUpListResDto> resDtoList = new ArrayList<FollowUpListResDto>();
		if (!CollectionUtils.isEmpty(fulist)) {
			FollowUpListResDto followUpListResDto = null;
			for (FollowUpList followUp : fulist) {
				followUpListResDto = FollowUpListConvert.convertModel2DTO(followUp);
				PartnerInfo partnerInfo = partnerInfoService.selectById(followUp.getStaffId());
				if (partnerInfo != null) {
					followUpListResDto.setStaffName(partnerInfo.getAccountName());
				}
				if (StringUtils.isNotEmpty(followUp.getRemark())) {
					if (followUp.getRemark().indexOf("申请带看") != -1) {
						SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
						followUpListResDto.setCreateTime(df.parse(followUp.getApplyLookDay()));
					}
				}

				List<AffixDto> affixList = affixService.listAffix(followUp.getId());
				followUpListResDto.setAffixList(affixList);
				resDtoList.add(followUpListResDto);
			}
		}

		res.setFollowList(resDtoList);
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}

	@Override
	public GetCPFollowStatusListResDto getCPFollowStatusList(
			GetCPFollowStatusListReqDto reqDto) throws Exception {
		GetCPFollowStatusListResDto res = new GetCPFollowStatusListResDto();
		CustomerPremises customerPremises = customerPremisesService.selectById(reqDto.getId());
		Map<String, String> map = customerPremisesService.getCusStatus(customerPremises);
		res.setMap(map);
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}

	@Override
	public IsInSpecialTimeResDto IsInSpecialTime(IsInSpecialTimeReqDto reqDto)
			throws Exception {
		IsInSpecialTimeResDto res = new IsInSpecialTimeResDto();
		res.setResult(ResultEnum.SUCCESS.getNo());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Calendar calendar = Calendar.getInstance();
		String hopeTime = reqDto.getHopeTime();
		if (StringUtils.isBlank(hopeTime)) {
			throw new TServerException("期望带看时间不能为空！");
		}
		Long premisesId = reqDto.getPremisesId();
		if (premisesId == null || premisesId == 0) {
			throw new TServerException("报备楼盘不能为空！");
		}
		Long hopeTimes = sdf.parse(hopeTime).getTime();
		if (hopeTimes < calendar.getTime().getTime()) {
			res.setMsg("3");
			return res;
		}

		Premises pre = premisesService.selectSimpleById(premisesId);
		if (pre == null) {
			throw new TServerException("该楼盘不存在或已被删除!");
		}
		//最短报备时间限制
		if (pre.getSpecialTimeType() != null && !TimeUnitTypeEnum.NONE.getNo().equals(pre.getSpecialTimeType())) {
			String specialTime = pre.getSpecialTime();
			//该数据存入数据库的时候已经转为分钟，这里无需再转
			calendar.add(Calendar.MINUTE, +Integer.parseInt(specialTime));
			Long specialTimeS = calendar.getTime().getTime();
			if (hopeTimes < specialTimeS) {
				throw new TServerException("该楼盘不支持临时报备，请按照要求提前报备！");
			}
		}
		res.setMsg("2");
		return res;
	}

	@Override
	public AddFollowResDto addFollow(AddFollowReqDto reqDto) {
		if (StringUtils.isBlank(reqDto.getUserId())) {
			throw new TServerException("用户id为空");
		}
		AddFollowResDto res = new AddFollowResDto();
		CustomerPremises customerPremises = customerPremisesService.selectById(reqDto.getCustomerPremisesId());
		Premises premises = premisesService.selectSimpleById(customerPremises.getPremisesId());
		String oldConfirmStatus = customerPremises.getConfirmStatus();
		String newConfirmStatus = customerPremises.getConfirmStatus();
		String oldCustomerStatus = customerPremises.getCustomerStatus();
		String newCustoemrStatus = customerPremises.getCustomerStatus();
		String commissionStatus = customerPremises.getCommissionStatus();
		String visitState = customerPremises.getVisitState();
		CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
		boolean needUpdate = false;
		if (StringUtils.isNotBlank(reqDto.getAdviser())) {
			if (!reqDto.getAdviser().equals(customerPremises.getAdviserUuid())) {
				customerPremisesDto.setId(customerPremises.getId());
				customerPremisesDto.setAdviserUuid(reqDto.getAdviser());
				needUpdate = true;
				adviserChangeDao.addAdviserChange(Arrays.asList(customerPremises), reqDto.getAdviser(), reqDto.getUserId());
			}
		}

		// 新增跟进信息
		FollowUpListDto follow = new FollowUpListDto();
		follow.setStaffId(Long.parseLong(reqDto.getUserId()));
		follow.setCustomerPremisesId(reqDto.getCustomerPremisesId());
		follow.setOldConfirmStatus(oldConfirmStatus);
		follow.setNewConfirmStatus(newConfirmStatus);
		follow.setOldCustomerStatus(oldCustomerStatus);
		follow.setNewCustomerStatus(newCustoemrStatus);
		follow.setNewCommissionStatus(commissionStatus);
		follow.setOldCommissionStatus(commissionStatus);
		if ("1".equals(reqDto.getFollowType()) || "2".equals(reqDto.getFollowType()) || "3".equals(reqDto.getFollowType())) {
			follow.setFollowUpType(FollowUpEnum.customer_follow.getNo());
			// 到访跟进(复访)
			if ("3".equals(reqDto.getFollowType())) {
				needUpdate = true;
				Date actualVisitTime = reqDto.getCreateTime();
				Date visitDate = new Date();
				if (Objects.nonNull(actualVisitTime)) {
					visitDate = actualVisitTime;
				}
				customerPremisesDto.setVisitTime(visitDate);
				// 到访保护时间有设置,并且复访开关开启
				if (StringUtils.isNotBlank(premises.getVisitBaohu()) && VisitBaohuRepeatEnum.OPEN.getNo().equals(premises.getVisitBaohuRepeat())) {
					customerPremisesDto.setId(reqDto.getCustomerPremisesId());
					visitDate = DateUtils.addMinute(visitDate, Integer.valueOf(premises.getVisitBaohu()));
					customerPremisesDto.setVisitBaohuTime(visitDate);
				}
				SyncReportRevisitToV10Dto toV10Dto = new SyncReportRevisitToV10Dto();
				toV10Dto.setRemark(reqDto.getRemark());
				toV10Dto.setVisitTime(customerPremisesDto.getVisitTime() == null ? null : DateUtils.DateToString(customerPremisesDto.getVisitTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
				reportCommonService.syncReportRevisitToV10(toV10Dto, customerPremises, reqDto.getAffixList());
			}
			if ("0".equals(visitState) || "1".equals(visitState) || "2".equals(visitState) || "3".equals(visitState)) {
				customerPremisesDto.setId(reqDto.getCustomerPremisesId());
				customerPremisesDto.setVisitState(Integer.valueOf(visitState) + 1 + "");
				needUpdate = true;
			}
		}
		if (needUpdate) {
			customerPremisesService.update(customerPremisesDto);
		}
		follow.setRemark(setRemark(reqDto));
		// 如果类型是巧渠道内部跟进，则跟进类型为内部跟进，其他情况不变
		if (FollowTypeEnum.INTERNAL.getNo().equals(reqDto.getFollowType())) {
			follow.setFollowType(FollowTypeEnum.INTERNAL.getNo());
			//内部跟进不对外通知
			reqDto.setSyncFlag("0");
			reqDto.setSendSms("0");
		} else {
			follow.setFollowType(FollowTypeEnum.DEVELOPERS.getNo());
		}
		EstateAdviser adviser = estateAdviserService.getAdviserByUuid(reqDto.getAdviser());
		logger.info("addFollow -----> adviser{}",adviser);
		if (null != adviser && !Strings.isStringEmpty(adviser.getName())){
			follow.setAdviser(adviser.getName());
		}
		follow.setVisitTime(StringUtils.isBlank(reqDto.getVisitTime()) ? reqDto.getCreateTime() : DateUtils.StringToDate(reqDto.getVisitTime(), "yyyy-MM-dd HH:mm:ss"));
		follow.setVisitedCount(setVisitedCount(reqDto));
		follow = followUpListService.create(follow);
		//保存附件
		List<AffixDto> affixList = reqDto.getAffixList();
		if (!CollectionUtils.isEmpty(affixList)) {
			for (AffixDto dto : affixList) {
				dto.setReportId(reqDto.getCustomerPremisesId());
				dto.setFollowUpListId(follow.getId());
				dto.setAffixUuid(UUID.randomUUID().toString());
				dto.setIsQiNiu(Boolean.TRUE);
				if(Objects.nonNull(dto.getIsQiNiu())){
					dto.setIsQiNiu(dto.getIsQiNiu());
				}
				dto.setAffixType("other");
				if (StringUtils.isEmpty(dto.getFileType()) && StringUtils.isNotEmpty(dto.getUrl())) {
					String[] fileTypes = dto.getUrl().split("\\.");
					if (fileTypes.length > 0) {
						dto.setFileType(fileTypes[fileTypes.length - 1]);
					}
				}
			}
			affixService.addAffixBatch(affixList);
		}
		//同步跟进和附件到V10
		if ("1".equals(reqDto.getSyncFlag())) {
			//获取报备绑定关系
			ReportExternalDto reportExternalDto = new ReportExternalDto();
			reportExternalDto.setReportId(reqDto.getCustomerPremisesId());
			reportExternalDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
			List<ReportExternal> list = reportExternalService.selectListByDto(reportExternalDto);
			if (!CollectionUtils.isEmpty(list)) {
				SyncFollowAndAffixReqDto syncReqDto = new SyncFollowAndAffixReqDto();
				V10IntentionFollowDto followVo = new V10IntentionFollowDto();
				followVo.setIntentionUuid(list.get(0).getReportUuid());
				followVo.setOperationType(OperationTypeEnum.OPERATIONTYPE_6.getCode());
				followVo.setRemark(reqDto.getRemark());
				followVo.setOldAuditStatus(oldCustomerStatus);
				followVo.setNewAuditStatus(newCustoemrStatus);
				syncReqDto.setFollowVo(followVo);
				if (!CollectionUtils.isEmpty(affixList)) {
					List<V10AffixDto> v10AffixList = new ArrayList<V10AffixDto>();
					V10AffixDto v10AffixDto = null;
					for (AffixDto affix : affixList) {
						v10AffixDto = new V10AffixDto();
						v10AffixDto.setAffixName(affix.getAffixName());
						v10AffixDto.setAffixType(affix.getAffixType());
						v10AffixDto.setChannelAffixUuid(affix.getAffixUuid());
						v10AffixDto.setIntentionUuid(list.get(0).getReportUuid());
						v10AffixDto.setIsQiNiu(Boolean.TRUE);
						if(Objects.nonNull(affix.getIsQiNiu())){
							v10AffixDto.setIsQiNiu(affix.getIsQiNiu());
						}
						v10AffixDto.setUrl(affix.getUrl());
						v10AffixDto.setFileType(affix.getFileType());
						v10AffixList.add(v10AffixDto);
					}
					syncReqDto.setAffixList(v10AffixList);
				}
				v10BindService.syncFollowAndAffix(syncReqDto, list.get(0).getPremisesUuid());
			}
		}

		// 发送跟进信息提醒
		if (reqDto.getSendFollowMsg()) {
			wxTemplateMsgService.sendFollowTemplateMsg(reqDto.getAssistantAccessToken(), reqDto.getCompanyUuid(), reqDto.getCustomerPremisesId());
		}
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setResultMsg("操作成功");
		return res;
	}

	private void sendReportSms(PartnerInfo assistantPi, CustomerPremises customerPremises, Map<String, String> smsMap) {
		//查询楼盘相关案场助手人员,发短信用
		CaseMemberDto cmDto = new CaseMemberDto();
		cmDto.setPremisesId(customerPremises.getPremisesId());
		cmDto.setPiStatus(MechanismStatusEnum.enable.getNo());
		cmDto.setSmsStatus("1");
		List<CaseMember> cmList = new ArrayList<CaseMember>();

		boolean flag = companyService.getMessageFlag(assistantPi.getHigherid());
		logger.info("商户 [ " + assistantPi.getHigherid() + "], 短信通道是否打开: " + flag);
		if (flag) {
			//需要发短信，就查询接收短信相关人员
			cmList = caseMemberService.selectListByDto(cmDto);
		}
		//发送短信
		try {
			if (!CollectionUtils.isEmpty(cmList)) {
				//报备客户,给楼盘对应的管理员发送短信
				String smsSwitch = smsUtil.getSmsSwitch();
				if (StringUtils.isNotEmpty(smsSwitch) && "T".equals(smsSwitch)) {
					String smsTemp = SMSTypeEnum.TYPE_15.getNo();
					DictionaryDto dicDto = new DictionaryDto();
					dicDto.setDicType(smsTemp);
					Dictionary dic = dictionaryService.selectByDto(dicDto);
					if (null != dic) {
						for (CaseMember cm : cmList) {

							String receiveMobile = "";
							PartnerInfo cmPi = partnerInfoService.selectById(cm.getPartnerId());
							if (null != cmPi) {
								receiveMobile = cmPi.getPhone();
							}
							if (StringUtils.isEmpty(receiveMobile)) {
								continue;
							}
							String smsContent = dic.getDicValue();

							String name = customerPremises.getName();//客户姓名
							String mobile = customerPremises.getMobile();//客户手机号
							String premisesName = smsMap.get("premisesName");//带看项目名称
							String staffName = assistantPi.getAccountName();//经济人姓名
							String staffMobile = assistantPi.getPhone();//经济人电话
							String adviser = smsMap.get("adviser");
							String visitTime = smsMap.get("visitTime");
							if (StringUtils.isBlank(adviser)) {
								adviser = "--";
							}
							if (StringUtils.isBlank(visitTime)) {
								visitTime = "--";
							} else {
								if (visitTime.length() > 3) {
									visitTime = visitTime.substring(0, visitTime.length() - 3);
								}

							}
							smsContent = String.format(smsContent, name, mobile, visitTime, premisesName, adviser, staffName, staffMobile);

							//获取短信设置,功能已变更.设置已用于定制化号码验真.此处不能保留
							Map<String, String> smsSettingMap = null;
//    	                	Map<String, String> smsSettingMap = smsSettingService.getSmsSettingMap(null, cm.getCompanyId(),null);

							Map<String, String> qfSmsMap = new HashMap<>();
							qfSmsMap.put("key1", name);
							qfSmsMap.put("key2", mobile);
							qfSmsMap.put("key3", visitTime);
							qfSmsMap.put("key4", premisesName);
							qfSmsMap.put("key5", adviser);
							qfSmsMap.put("key6", staffName);
							qfSmsMap.put("key7", staffMobile);

							Map<String, Object> returnMap = smsUtil.sendMessage(smsContent, receiveMobile, QfSmsTemplateEnum.SMS_WARN_AUDIT.getId(), smsSettingMap, qfSmsMap);
							boolean sendStatus = (Boolean) returnMap.get("sendStatus");
							String sendRes = String.valueOf(returnMap.get("sendRes"));
							SmsHistoryDto smsHis = new SmsHistoryDto();
							smsHis.setSender(smsUtil.getUserName());
							if (null != smsSettingMap) {
								smsHis.setSender(smsSettingMap.get("userName"));
							}
							smsHis.setReceiver(receiveMobile);
							smsHis.setContent(smsContent);
							smsHis.setSendStatus(sendStatus ? SendStatusEnum.SUCCESS.getNo() : SendStatusEnum.FAILURE.getNo());
							smsHis.setSendRes(sendRes);
							smsHis.setMerchantId(cmPi.getHigherid());
							smsHis.setRemark("提醒到访审核!");
							smsHis.setCreateUserId(assistantPi.getId());
							if (returnMap.containsKey("orderUuid")) {
								smsHis.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
							}
							if (returnMap.containsKey("platform")) {
								smsHis.setPlatform(String.valueOf(returnMap.get("platform")));
							}
							smsHistoryService.create(smsHis);
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("SyncFollowAndAffixServiceImpl error: {}", e);
		}
	}

	private String setRemark(AddFollowReqDto reqDto) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//跟进类型
		if (StringUtils.isBlank(reqDto.getFollowType())) {
			return reqDto.getRemark();
		}
		if ("1".equals(reqDto.getFollowType())) {
			return "【普通跟进】" + reqDto.getRemark();
		}
		if ("2".equals(reqDto.getFollowType())) {
			return "【电话跟进】" + reqDto.getRemark();
		}
		if ("3".equals(reqDto.getFollowType())) {
			return "【到访】" + sdf.format(reqDto.getCreateTime()) + " " + reqDto.getRemark();
		}
		if ("4".equals(reqDto.getFollowType())) {
			return "【内部跟进】" + reqDto.getRemark();
		}
		return reqDto.getRemark();
	}

	// 查询是否为多次到访
	private Integer setVisitedCount(AddFollowReqDto reqDto) {
		if (!"3".equals(reqDto.getFollowType())) {
			return null;
		}
		//查询到访数据
		FollowUpListDto followUpListDto = new FollowUpListDto();
		followUpListDto.setCustomerPremisesId(reqDto.getCustomerPremisesId());
		followUpListDto.setNewConfirmStatus(ConfirmStatusEnum.confirm.getNo());
		followUpListDto.setOldConfirmStatus(ConfirmStatusEnum.confirm.getNo());
		followUpListDto.setNewCustomerStatus(CustomerStatusEnum.has_visited.getNo());
//		followUpListDto.setOldCustomerStatus(CustomerStatusEnum.not_visited.getNo());

		FollowUpList followUpList = followUpListService.getLastVisitedFollowUpList(followUpListDto);
		if (followUpList == null || new Integer(0).equals(followUpList.getVisitedCount())) {
			//算上第一次
			return 2;
		} else {
			return followUpList.getVisitedCount() + 1;
		}

	}
}
